package kr.co.graviti.common.model;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;

import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

@Repository
public class MultipartUploadFileRepository {
	
	public MultipartUploadFile registFile(String prefix,String uploadPath
			, MultipartFile file) {
		
		String originalFilename = file.getOriginalFilename();
		long filesize = file.getSize();
		
		String contentType = file.getContentType();
		
		InputStream is = null;
		OutputStream os = null;
		
		//String uploadFilename =  getFilename(uploadPath, originalFilename);
		String uploadFilename	= getReFileNm(prefix, uploadPath, originalFilename);
		try {
			if (filesize > 0) {
				is = file.getInputStream();
				File fileUploadPath = new File(uploadPath);
				if (!fileUploadPath.exists()) {
					fileUploadPath.mkdirs();
				}
				
				os = new FileOutputStream(new StringBuffer(uploadPath).append("/").append(uploadFilename).toString());
				
				int bytes = 0;
				byte [] bufferbyte = new byte[1024];
				
				while ((bytes = is.read(bufferbyte, 0, 1024)) != -1) {
					os.write(bufferbyte, 0, bytes);
				}
			}
		} catch (IOException ioe) {
			// TODO: handle exception
			ioe.printStackTrace();
		} finally {
			try {
				os.close();
				is.close();
			} catch (IOException ioe2) {
				// TODO: handle exception
				ioe2.printStackTrace();
			}
		}
		
		MultipartUploadFile multipartUploadFile = new MultipartUploadFile();
		multipartUploadFile.setFilename(uploadFilename);
		multipartUploadFile.setOrginalFilename(originalFilename);
		multipartUploadFile.setFilesize(filesize);
		multipartUploadFile.setContentType(contentType);
		multipartUploadFile.setUploadPath(uploadPath);
		
		return multipartUploadFile;
		
	}
	
	private String getFilename(String uploadPath, String filename) {
		
		if (filename.indexOf(" ") > -1)
			filename = filename.trim();
		
		File f = new File(uploadPath, filename);
		
		if (f.exists()) {
			int i = filename.lastIndexOf('.');
			if (i < 0) {
				i = filename.length();
			}
			String prefix = filename.substring(0, i);
			String suffix = filename.substring(i);
			int n = 2;
			
			do {
				f = new File(uploadPath, prefix + "[" + n + "]" + suffix);
				n ++;
			} while (f.exists());
		}
		
		return f.getName();
	}
	
	/** rename
	 * @param prefix
	 * @param uploadDir
	 * @param orgFileName
	 * @return
	 */
	public String getReFileNm(String prefix, String uploadDir, String orgFileName) {
		
		String changeFilename = "";
		String orgExt = "";
		
		orgExt = orgFileName.split("\\.")[orgFileName.split("\\.").length-1];
		File orgf = new File(new StringBuffer(uploadDir).append("/").append(orgFileName).toString());
		changeFilename = new StringBuffer(prefix).append("_").append(getCurDateSec2()).toString();
		changeFilename = new StringBuffer(changeFilename).append(".").append(orgExt).toString();
		orgf.renameTo(new File(new StringBuffer(uploadDir).append("/").append(changeFilename).toString()));	
		
		return changeFilename;
	}
	 /**
     * 오늘날짜초까지 리턴 한글 없음
     */
     public static String getCurDateSec2() {
         SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMddhhmmss"); 
         String curDate = dateFormatter.format(new java.util.Date()); 
         return curDate; 
     }
     /**
      * 지정된 범위안에서의 난수발
      * @param n1	최대값
      * @param n2	최소값
      * @return		난수 
      */
 	public static int randomRange(int n1, int n2) {
     	return (int) (Math.random() * (n2 - n1 + 1)) + n1;
   	}

}
